import { useState, useEffect } from "react";
import {
  Table,
  Input,
  Button,
  Space,
  message,
  Select,
  Modal,
} from "antd";
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import CommonFormModal from "../../components/CommonFormModal";
import { useFormModal } from "../../hooks/useFormModal";
import { storageLocationFormConfig } from "../../utils/formConfigs";

// API 基础配置
const API_BASE_URL = 'http://localhost:3000';

const { Search } = Input;
const { Option } = Select;

// 定义通用选项类型接口
interface OptionItem {
  value: string;
  label: string;
}

// 库位数据接口定义（与后端 API 匹配）
interface StorageLocation {
  id: number;
  code: string;
  location: string;
  warehouseId: number;
  warehouseCode: string;
  reservoirId: number;
  reservoirCode: string;
  affiliated: string;
  affiliatedReservoir: string;
  add: string;
  addtime: string;
  edit: string;
  edittime: string;
}

// 表单字段类型定义（已移除，使用通用表单组件）

// 模拟库位数据
const mockStorageLocationData: StorageLocation[] = [
  {
    key: "1",
    id: "3001",
    code: "SL001",
    name: "食品架1",
    warehouseName: "食品B仓",
    areaName: "零食区",
    locationType: "货架",
    status: "正常",
    creator: "admin",
    createTime: "2020-02-15",
    modifier: "admin",
    modifyTime: "2021-03-10",
  },
  {
    key: "2",
    id: "3002",
    code: "SL002",
    name: "日用品架2",
    warehouseName: "日用品C仓",
    areaName: "洗漱区",
    locationType: "货架",
    status: "正常",
    creator: "user1",
    createTime: "2020-03-10",
    modifier: "user2",
    modifyTime: "2021-04-05",
  },
  {
    key: "3",
    id: "3003",
    code: "SL003",
    name: "家电地堆3",
    warehouseName: "家电D仓",
    areaName: "小家电区",
    locationType: "地堆",
    status: "维护中",
    creator: "admin",
    createTime: "2020-04-05",
    modifier: "admin",
    modifyTime: "2021-05-20",
  },
  {
    key: "4",
    id: "3004",
    code: "SL004",
    name: "服装挂架4",
    warehouseName: "服装E仓",
    areaName: "男装区",
    locationType: "挂架",
    status: "正常",
    creator: "user2",
    createTime: "2020-05-20",
    modifier: "user3",
    modifyTime: "2021-06-12",
  },
  {
    key: "5",
    id: "3005",
    code: "SL005",
    name: "生鲜冷藏架5",
    warehouseName: "生鲜A仓",
    areaName: "生鲜冷藏区",
    locationType: "冷藏架",
    status: "正常",
    creator: "admin",
    createTime: "2020-01-22",
    modifier: "admin",
    modifyTime: "2021-02-25",
  },
  {
    key: "6",
    id: "3006",
    code: "SL006",
    name: "生鲜冷冻柜6",
    warehouseName: "生鲜A仓",
    areaName: "生鲜冷冻区",
    locationType: "冷冻柜",
    status: "故障",
    creator: "user3",
    createTime: "2020-01-25",
    modifier: "admin",
    modifyTime: "2021-03-15",
  },
  {
    key: "7",
    id: "3007",
    code: "SL007",
    name: "饮料冷藏柜7",
    warehouseName: "食品B仓",
    areaName: "饮料区",
    locationType: "冷藏柜",
    status: "正常",
    creator: "admin",
    createTime: "2020-02-20",
    modifier: "user1",
    modifyTime: "2021-04-20",
  },
];

// 模拟所属仓库下拉选项数据
const mockWarehouseOptions: OptionItem[] = [
  { value: "生鲜A仓", label: "生鲜A仓" },
  { value: "食品B仓", label: "食品B仓" },
  { value: "日用品C仓", label: "日用品C仓" },
  { value: "家电D仓", label: "家电D仓" },
  { value: "服装E仓", label: "服装E仓" },
];

// 模拟所属库区下拉选项数据
const mockAreaOptions: Record<string, OptionItem[]> = {
  生鲜A仓: [
    { value: "生鲜冷藏区", label: "生鲜冷藏区" },
    { value: "生鲜冷冻区", label: "生鲜冷冻区" },
  ],
  食品B仓: [
    { value: "零食区", label: "零食区" },
    { value: "饮料区", label: "饮料区" },
  ],
  日用品C仓: [
    { value: "洗漱区", label: "洗漱区" },
    { value: "清洁区", label: "清洁区" },
  ],
  家电D仓: [
    { value: "小家电区", label: "小家电区" },
    { value: "大家电区", label: "大家电区" },
  ],
  服装E仓: [
    { value: "男装区", label: "男装区" },
    { value: "女装区", label: "女装区" },
  ],
};

// 库位状态选项
const statusOptions: OptionItem[] = [
  { value: "正常", label: "正常" },
  { value: "维护中", label: "维护中" },
  { value: "故障", label: "故障" },
  { value: "闲置", label: "闲置" },
];

export default function StorageLocationManagement() {
  // 全局紧凑样式
  const compactStyle = {
    fontSize: "12px",
    padding: "2px 5px",
  };

  const [storageLocationData, setStorageLocationData] = useState<
    StorageLocation[]
  >([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    locationCode: "",
    locationName: "",
    warehouse: undefined as string | undefined,
    area: undefined as string | undefined,
    status: undefined as string | undefined,
  });
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [areaOptions, setAreaOptions] = useState<OptionItem[]>([]);
  const [warehouseOptions, setWarehouseOptions] = useState<OptionItem[]>([]);
  const [reservoirOptions, setReservoirOptions] = useState<OptionItem[]>([]);

  // 使用通用表单Hook
  const {
    visible,
    isAddMode,
    currentRecord,
    loading: formLoading,
    openAddModal,
    openEditModal,
    closeModal,
  } = useFormModal<StorageLocation>();

  // 获取库位数据
  const fetchStorageData = async () => {
    try {
      setLoading(true);
      const response = await fetch(`${API_BASE_URL}/api/storage`);
      if (!response.ok) {
        throw new Error('获取库位数据失败');
      }
      const data = await response.json();
      setStorageLocationData(data);
    } catch (error) {
      console.error('获取库位数据失败:', error);
      message.error('获取库位数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取仓库选项
  const fetchWarehouseOptions = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/warehouse`);
      if (!response.ok) {
        throw new Error('获取仓库数据失败');
      }
      const data = await response.json();
      const options = data.map((item: any) => ({
        value: item.name,
        label: item.name,
        warehouseId: item.id,
        warehouseCode: item.code,
      }));
      setWarehouseOptions(options);
    } catch (error) {
      console.error('获取仓库数据失败:', error);
      message.error('获取仓库数据失败');
    }
  };

  // 获取库区选项
  const fetchReservoirOptions = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/reservoir`);
      if (!response.ok) {
        throw new Error('获取库区数据失败');
      }
      const data = await response.json();
      const options = data.map((item: any) => ({
        value: item.name,
        label: item.name,
        reservoirId: item.id,
        reservoirCode: item.code,
        warehouseId: item.warehouseId,
        affiliated: item.affiliated,
      }));
      setReservoirOptions(options);
    } catch (error) {
      console.error('获取库区数据失败:', error);
      message.error('获取库区数据失败');
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchStorageData();
    fetchWarehouseOptions();
    fetchReservoirOptions();
  }, []);

  // 监听仓库选择，动态加载库区选项
  useEffect(() => {
    if (searchParams.warehouse) {
      const filteredReservoirs = reservoirOptions.filter(
        (reservoir: any) => reservoir.affiliated === searchParams.warehouse
      );
      setAreaOptions(filteredReservoirs);
    } else {
      setAreaOptions([]);
    }
  }, [searchParams.warehouse, reservoirOptions]);

  // 表单中仓库变更时更新库区选项（已移除，使用通用表单组件）

  // 处理搜索
  const handleSearch = async () => {
    try {
      setLoading(true);
      const response = await fetch(`${API_BASE_URL}/api/storage`);
      if (!response.ok) {
        throw new Error('搜索库位数据失败');
      }
      const data = await response.json();
      
      const filteredData = data.filter((item: StorageLocation) => {
        return (
          (searchParams.locationCode === "" ||
            item.code.includes(searchParams.locationCode)) &&
          (searchParams.locationName === "" ||
            item.location.includes(searchParams.locationName)) &&
          (searchParams.warehouse === undefined ||
            item.affiliated === searchParams.warehouse) &&
          (searchParams.area === undefined ||
            item.affiliatedReservoir === searchParams.area)
        );
      });
      setStorageLocationData(filteredData);
      message.success(`找到 ${filteredData.length} 条匹配记录`);
    } catch (error) {
      console.error('搜索库位数据失败:', error);
      message.error('搜索库位数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理重置
  const handleReset = () => {
    setSearchParams({
      locationCode: "",
      locationName: "",
      warehouse: undefined,
      area: undefined,
      status: undefined,
    });
    fetchStorageData();
    setAreaOptions([]);
    message.info("已重置搜索条件");
  };

  // 处理新增库位
  const handleAddLocation = () => {
    setAreaOptions([]);
    openAddModal();
  };

  // 处理编辑库位
  const handleEdit = (record: StorageLocation) => {
    const filteredReservoirs = reservoirOptions.filter(
      (reservoir: any) => reservoir.affiliated === record.affiliated
    );
    setAreaOptions(filteredReservoirs);
    openEditModal(record);
  };

  // 确认删除
  const handleDelete = (record: StorageLocation) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除库位 "${record.location}" 吗？此操作不可撤销。`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          const response = await fetch(`${API_BASE_URL}/api/storage/${record.id}`, {
            method: 'DELETE',
          });
          if (!response.ok) {
            throw new Error('删除库位失败');
          }
          await fetchStorageData();
          message.success(`库位 "${record.location}" 已删除`);
        } catch (error) {
          console.error('删除库位失败:', error);
          message.error('删除库位失败');
        }
      },
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRows.length === 0) {
      message.warning("请先选择要删除的库位");
      return;
    }

    Modal.confirm({
      title: "批量删除",
      content: `确定要删除选中的 ${selectedRows.length} 个库位吗？此操作不可撤销。`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          const deletePromises = selectedRows.map(id => 
            fetch(`${API_BASE_URL}/api/storage/${id}`, {
              method: 'DELETE',
            })
          );
          await Promise.all(deletePromises);
          await fetchStorageData();
          setSelectedRows([]);
          message.success(`已删除 ${selectedRows.length} 个库位`);
        } catch (error) {
          console.error('批量删除库位失败:', error);
          message.error('批量删除库位失败');
        }
      },
    });
  };

  // 处理表单提交
  const handleSubmit = async (values: Record<string, unknown>, isAddMode: boolean, currentRecord?: StorageLocation | null) => {
    try {
      if (isAddMode) {
        // 新增操作
        const response = await fetch(`${API_BASE_URL}/api/storage`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            code: values.code,
            location: values.name,
            warehouseId: values.warehouseId,
            warehouseCode: values.warehouseCode,
            reservoirId: values.reservoirId,
            reservoirCode: values.reservoirCode,
            affiliated: values.warehouse,
            affiliatedReservoir: values.area,
            add: "admin",
            addtime: new Date().toISOString().split('T')[0],
            edit: "admin",
            edittime: new Date().toISOString().split('T')[0],
          }),
        });
        if (!response.ok) {
          throw new Error('创建库位失败');
        }
        await fetchStorageData();
        message.success(`库位 "${values.name}" 已创建`);
      } else {
        // 编辑操作
        if (currentRecord) {
          const response = await fetch(`${API_BASE_URL}/api/storage/${currentRecord.id}`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              code: values.code,
              location: values.name,
              warehouseId: values.warehouseId,
              warehouseCode: values.warehouseCode,
              reservoirId: values.reservoirId,
              reservoirCode: values.reservoirCode,
              affiliated: values.warehouse,
              affiliatedReservoir: values.area,
              edit: "admin",
              edittime: new Date().toISOString().split('T')[0],
            }),
          });
          if (!response.ok) {
            throw new Error('更新库位失败');
          }
          await fetchStorageData();
          message.success(`库位 "${values.name}" 已更新`);
        }
      }
    } catch (error) {
      console.error('提交库位数据失败:', error);
      message.error('提交库位数据失败');
    }
  };

  // 表格列配置（紧凑版）
  const columns = [
    {
      title: "",
      dataIndex: "checkbox",
      key: "checkbox",
      width: 30,
      render: (_: any, record: StorageLocation) => (
        <Input
          type="checkbox"
          checked={selectedRows.includes(record.id)}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedRows([...selectedRows, record.id]);
            } else {
              setSelectedRows(selectedRows.filter((id) => id !== record.id));
            }
          }}
          style={compactStyle}
        />
      ),
    },
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      width: 50,
      render: (text: number) => (
        <a href="#" style={compactStyle}>
          {text}
        </a>
      ),
    },
    {
      title: "编码",
      dataIndex: "code",
      key: "code",
      width: 70,
      style: compactStyle,
    },
    {
      title: "库位名称",
      dataIndex: "location",
      key: "location",
      width: 80,
      style: compactStyle,
    },
    {
      title: "所属仓库",
      dataIndex: "affiliated",
      key: "affiliated",
      width: 80,
      style: compactStyle,
    },
    {
      title: "所属库区",
      dataIndex: "affiliatedReservoir",
      key: "affiliatedReservoir",
      width: 80,
      style: compactStyle,
    },
    {
      title: "仓库编码",
      dataIndex: "warehouseCode",
      key: "warehouseCode",
      width: 80,
      style: compactStyle,
    },
    {
      title: "库区编码",
      dataIndex: "reservoirCode",
      key: "reservoirCode",
      width: 80,
      style: compactStyle,
    },
    {
      title: "创建人",
      dataIndex: "add",
      key: "add",
      width: 60,
      style: compactStyle,
    },
    {
      title: "创建时间",
      dataIndex: "addtime",
      key: "addtime",
      width: 80,
      style: compactStyle,
    },
    {
      title: "修改人",
      dataIndex: "edit",
      key: "edit",
      width: 60,
      render: (text: string) => (
        <a href="#" style={compactStyle}>
          {text}
        </a>
      ),
    },
    {
      title: "修改时间",
      dataIndex: "edittime",
      key: "edittime",
      width: 80,
      render: (text: string) => (
        <a href="#" style={compactStyle}>
          {text}
        </a>
      ),
    },
    {
      title: "操作",
      key: "operation",
      width: 130,
      render: (_: any, record: StorageLocation) => (
        <Space size="small" style={compactStyle}>
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              handleEdit(record);
            }}
            style={compactStyle}
          >
            <EditOutlined style={{ fontSize: "12px" }} /> 编辑
          </a>
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              handleDelete(record);
            }}
            style={compactStyle}
          >
            <DeleteOutlined style={{ fontSize: "12px" }} /> 删除
          </a>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: "12px", fontSize: "12px" }}>
      {/* 搜索区域（紧凑版） */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          marginBottom: "12px",
          flexWrap: "wrap",
          gap: "8px",
        }}
      >
        <Search
          placeholder="库位编号"
          allowClear
          enterButton={<SearchOutlined style={{ fontSize: "12px" }} />}
          value={searchParams.locationCode}
          onChange={(e) =>
            setSearchParams({ ...searchParams, locationCode: e.target.value })
          }
          onSearch={handleSearch}
          style={{ width: 160, fontSize: "12px" }}
        />
        <Search
          placeholder="库位名称"
          allowClear
          enterButton={<SearchOutlined style={{ fontSize: "12px" }} />}
          value={searchParams.locationName}
          onChange={(e) =>
            setSearchParams({ ...searchParams, locationName: e.target.value })
          }
          onSearch={handleSearch}
          style={{ width: 160, fontSize: "12px" }}
        />
        <Select
          placeholder="所属仓库"
          style={{ width: 160, fontSize: "12px" }}
          value={searchParams.warehouse}
          onChange={(value) =>
            setSearchParams({
              ...searchParams,
              warehouse: value,
              area: undefined,
            })
          }
          showSearch
          optionFilterProp="children"
        >
          {warehouseOptions.map((option) => (
            <Option
              key={option.value}
              value={option.value}
              style={{ fontSize: "12px" }}
            >
              {option.label}
            </Option>
          ))}
        </Select>
        <Select
          placeholder="所属库区"
          style={{ width: 120, fontSize: "12px" }}
          value={searchParams.area}
          onChange={(value) =>
            setSearchParams({ ...searchParams, area: value })
          }
          showSearch
          optionFilterProp="children"
          disabled={!searchParams.warehouse}
        >
          {areaOptions.map((option) => (
            <Option
              key={option.value}
              value={option.value}
              style={{ fontSize: "12px" }}
            >
              {option.label}
            </Option>
          ))}
        </Select>
        <Select
          placeholder="状态"
          style={{ width: 100, fontSize: "12px" }}
          value={searchParams.status}
          onChange={(value) =>
            setSearchParams({ ...searchParams, status: value })
          }
          showSearch
          optionFilterProp="children"
        >
          {statusOptions.map((option) => (
            <Option
              key={option.value}
              value={option.value}
              style={{ fontSize: "12px" }}
            >
              {option.label}
            </Option>
          ))}
        </Select>
        <Button
          type="primary"
          size="small"
          onClick={handleSearch}
          style={{ fontSize: "12px", padding: "2px 12px" }}
        >
          搜索
        </Button>
        <Button
          size="small"
          onClick={handleReset}
          style={{ fontSize: "12px", padding: "2px 12px" }}
        >
          重置
        </Button>
      </div>

      {/* 按钮区域（紧凑版） */}
      <div style={{ marginBottom: "12px", display: "flex", gap: "8px" }}>
        <Button
          type="primary"
          icon={<PlusOutlined style={{ fontSize: "12px" }} />}
          onClick={handleAddLocation}
          size="small"
          style={{ fontSize: "12px", padding: "2px 12px" }}
        >
          新增库位
        </Button>
        {selectedRows.length > 0 && (
          <Button
            danger
            size="small"
            onClick={handleBatchDelete}
            style={{ fontSize: "12px", padding: "2px 12px" }}
          >
            批量删除
          </Button>
        )}
      </div>

      {/* 表格（紧凑版） */}
      <Table
        // 给列表加一个滑动样式
        scroll={{ x: "max-content" }}
        dataSource={storageLocationData}
        columns={columns}
        bordered
        rowKey="id"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: false,
          style: { fontSize: "12px" },
        }}
        size="small"
      />

      {/* 通用表单弹窗 */}
      <CommonFormModal
        visible={visible}
        title={isAddMode ? "新增库位" : "编辑库位"}
        isAddMode={isAddMode}
        currentRecord={currentRecord}
        formItems={storageLocationFormConfig}
        onSubmit={handleSubmit}
        onCancel={closeModal}
        loading={formLoading}
        width={450}
      />
    </div>
  );
}
